package com.bjc.sdx.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.appcompat.app.AppCompatActivity;

import com.bjc.sdx.R;

public class Activity3 extends AppCompatActivity {
    private ToggleButton button;
    private TextView text;
    BroadcastReceiver receiver = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (ToggleButton) findViewById(R.id.button);
        text = (TextView) findViewById(R.id.text);
        final BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                    int current = intent.getExtras().getInt("level");
                    int total = intent.getExtras().getInt("scale");
                    int value = current * 100 / total;
                    text.setText("当前电量是" + value + "%" + "");
                }
            }
        };
        button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                    registerReceiver(receiver, filter);
                } else {
                    unregisterReceiver(receiver);
                    text.setText("123456789");
                }
            }
        });
    }
}